package de.fmannan.addbook.views;

import java.util.LinkedList;

import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;

import de.fmannan.addbook.domainmodel.Contact;
import de.fmannan.addbook.domainmodel.Group;
import de.fmannan.addbook.domainmodel.GroupRegistrar;

public class TableViewContentProvider implements IStructuredContentProvider {

	private static final Logger log = Logger.getLogger(TableViewContentProvider.class);
	private ContactTableView contactTableView;
	private GroupRegistrar invisibleRoot;
	
	public TableViewContentProvider (ContactTableView contactTableView) {
		this.contactTableView = contactTableView;
	}
	
	@Override
	/**
	 * Returns all children (Contacts) in order to display them in a table view.
	 */
	public Object[] getElements(Object inputElement) {
		LinkedList<Contact> children = new LinkedList<Contact>();
		
		if (inputElement.equals(this.contactTableView.getViewSite())) {
			// If there is not root yet, we initialize the tree model by using
			// the parent as our root
			if (invisibleRoot == null){
				// An earlier attempt to lazy-initialize the GroupRegistrar here
				// led to buggy application behaviour because of which it has
				// been decided, that the GroupRegistrar should by up and
				// running by now anyway
				invisibleRoot = GroupRegistrar.getInstance();
			}
			// Get all Children from all Groups and add them to our LinkedList
			for(Object c : GroupRegistrar.getInstance().getChildren()) {
				for(Object o : ((Group)c).getChildren()) {
					children.add((Contact)o);
				}
			}
		}
		log.debug("Retrieving all children");
		return children.toArray();
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		// TODO Auto-generated method stub
		
	}
}
